package com.tianhui.consignortwofei.mvp.ui.activity;

import android.text.TextUtils;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;

import com.fgs.common.CommonFragment;
import com.fgs.common.CommonPresenter;
import com.fgs.common.CommonResponse;
import com.fgs.common.CommonView;
import com.fgs.common.progress.ExceptionHandle;
import com.fgs.common.progress.ObserverResponseListener;
import com.fgs.common.utils.CheckUtil;
import com.fgs.common.utils.CountDownTimerUtil;
import com.fgs.common.utils.LogUtil;
import com.fgs.common.utils.ToastUtil;
import com.fgs.common.widget.TextChange;
import com.google.gson.reflect.TypeToken;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.base.BaseActivity;
import com.tianhui.consignortwofei.mvp.model.AuthCodeModel;
import com.tianhui.consignortwofei.mvp.model.UserInfoModel;
import com.tianhui.consignortwofei.mvp.model.enty.CaptchaInfo;
import com.xuexiang.xui.widget.edittext.ClearEditText;
import com.xuexiang.xui.widget.edittext.PasswordEditText;
import com.xuexiang.xutil.net.JsonUtil;
import com.xuexiang.xutil.security.Base64Utils;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author fgs
 * @date 2020/3/30
 **/
public class ForgetPasswordActivity extends BaseActivity {


    @BindView(R.id.layout_register_forget_password_phoneClearEditText)
    ClearEditText phoneEditText;
    @BindView(R.id.layout_register_forget_password_codeEditText)
    ClearEditText codeEditText;
    @BindView(R.id.layout_register_forget_password_codeTextView)
    TextView codeTextView;
    @BindView(R.id.layout_register_forget_password_passwordEditText)
    PasswordEditText passwordEditText;
    @BindView(R.id.activity_forget_password_commitButton)
    Button commitButton;

    @BindView(R.id.wv_captcha)
    WebView wv_captcha;

    private UserInfoModel mModel;
    private AuthCodeModel mAuthCodeModel;

    @Override
    public int getLayoutId() {
        return R.layout.activity_forget_password;
    }

    @Override
    public CommonPresenter createPresenter() {
        return null;
    }

    @Override
    public String getToolbarTitle() {
        return "密码找回";
    }

    @Override
    public CommonView createView() {
        return null;
    }

    @Override
    public void init() {

        mModel = new UserInfoModel();
        mAuthCodeModel = new AuthCodeModel();

        new TextChange.Builder()
                .addEditText(phoneEditText, 11)
                .addEditText(codeEditText, 6)
                .addEditText(passwordEditText, 6)
                .addListenView(commitButton)
                .build();
        initWebView();
    }

    @Override
    public CommonFragment createFragment() {
        return null;
    }

    @OnClick(R.id.activity_forget_password_commitButton)
    public void commit() {


        String phone = phoneEditText.getText().toString().trim();
        String code = codeEditText.getText().toString().trim();
        String password = passwordEditText.getText().toString().trim();

        if (TextUtils.isEmpty(phone)) {
            ToastUtil.showShortToast("请输入手机号");
            return;
        }
        if (!CheckUtil.isMobileNO(phone)) {
            ToastUtil.showShortToast("请输入正确的手机号");
            return;
        }

        if (TextUtils.isEmpty(code)) {
            ToastUtil.showShortToast("请输入验证码");
            return;
        }
        if (code.length() < 6) {
            ToastUtil.showShortToast("验证码不能少与6位");
            return;
        }

        if (TextUtils.isEmpty(password)) {
            ToastUtil.showShortToast("请输入密码");
            return;
        }
        if (password.length() < 8) {
            ToastUtil.showShortToast("密码不能少与8位");
            return;
        }

//        if (!CheckUtil.isPasswordStrength(password)) {
//            ToastUtil.showShortToast("密码必须包含字母和数字");
//            return;
//        }

        Map<String, String> map = new HashMap<>();
        map.put("code", code);
        map.put("mobile", "+86" + phone);
        map.put("newPassword", Base64Utils.encode(password));
        requestResetPassword(map);
    }

    private void requestResetPassword(Map<String, String> map) {
        mModel.resetPasswordModel(this, map, true, true, this.bindToLifecycle(), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse baseResponse) {
                if (baseResponse.getCode() == 20000) {
                    finish();
                    openActivity(ResetPasswordSuccessActivity.class);
                } else {
                    showToast(baseResponse.getMsg());
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });
    }

    @OnClick(R.id.layout_register_forget_password_codeTextView)
    public void getAuthCode() {
        getYanZheng();
//        String phone = phoneEditText.getText().toString().trim();
//        new AuthCode(this, phone).authCode(new AuthCode.OnAuthCodeCallback() {
//            @Override
//            public void onAuthCallback(CaptchaInfo info) {
//                if (info.ret == 0) {
//
//                    info.action = "resetpasswd";
//                    info.mobile = "+86" + phone;
//                    requestAuthCode(info);
//                }
//            }
//        });
    }

    private void requestAuthCode(CaptchaInfo info) {
        mAuthCodeModel.authCodeModel(this, info, true, this.bindToLifecycle(), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse commonResponse) {
                if (commonResponse.getCode() == 20000) {
                    startCountDownTime();
                } else {
                    showToast(commonResponse.getMsg());
                }
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });
    }

    private void startCountDownTime() {
        new CountDownTimerUtil(codeTextView, 1000 * 60, 1000).start();
    }





    //验证码
    private void initWebView() {
        //如果要做成弹窗式的，那么这个webview就要设置成透明的，否则webview不透明会挡住主页面的布局
        wv_captcha.setBackgroundColor(0);
        WebSettings webSettings = wv_captcha.getSettings();
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        // 禁用缓存
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        wv_captcha.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });
        // 开启js支持
        webSettings.setJavaScriptEnabled(true);
        wv_captcha.addJavascriptInterface(new ForgetPasswordActivity.JsBridge(), "jsBridge");
        // 也可以加载本地html(webView.loadUrl("file:///android_asset/xxx.html"))
        //zh-hk，ja，en

//  wv_captcha.loadUrl("file:///android_asset/tencenweb.html?lan=zh-hk");
//        wv_captcha.loadUrl("file:///android_asset/tencenweb.html");


    }

    public class JsBridge {

        @JavascriptInterface
        public void getData(String data) {
            //回调结果：{"ret":2,"randstr":"","ticket":""}

            LogUtil.print("fei", data);
            CaptchaInfo info = JsonUtil.fromJson(data, new TypeToken<CaptchaInfo>() {
            }.getType());
            if (info.ret == 0) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 更新UI的代码
                        wv_captcha.setVisibility(View.GONE);
                    }
                });

                String phone = phoneEditText.getText().toString().trim();
                info.action = "resetpasswd";
                info.mobile = "+86" + phone;
                requestAuthCode(info);

            }else if (info.ret == 2){
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 更新UI的代码
                        wv_captcha.setVisibility(View.GONE);
                    }
                });
            }
        }
    }


    public void getYanZheng() {
        wv_captcha.setVisibility(View.VISIBLE);
        wv_captcha.loadUrl("file:///android_asset/tencenweb.html?lan=zh-hk");

    }







}
